package main

import (
	"bufio"
	"encoding/base64"
	"fmt"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	ocr "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/ocr/v20181119"
	"io/ioutil"
	"os"
	"strings"
)

var(
	secretId,secretKey string
)

func main() {

	println("请输入腾讯云secretId")
	fmt.Scanln(&secretId)
	println("请输入腾讯云secretKey")
	fmt.Scanln(&secretKey)

	if len(secretId)==0 {
		println("腾讯云secretId 为空，程序结束")
		return
	}
	if len(secretKey) ==0{
		println("腾讯云secretKey 为空，程序结束")
		return
	}
	println("当前secretId：",secretId)
	println("当前secretKey：",secretKey)

	credential := common.NewCredential(
		secretId,
		secretKey,
	)
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "ocr.tencentcloudapi.com"
	client, _ := ocr.NewClient(credential, "ap-shanghai", cpf)
	println("OCR========================START============================================START\n\n")
	files, _ := ioutil.ReadDir("./images")
	if len(files) == 0 {
		println("OCR-------警告-----images目录内没有文件")
	} else {
		for _, file := range files {
			println("OCR---" + file.Name() + "-----------------------START")
			if strings.Contains(file.Name(), ".png") || strings.Contains(file.Name(), ".PNG") || strings.Contains(file.Name(), ".JPG") || strings.Contains(file.Name(), ".jpg") || strings.Contains(file.Name(), ".JPEG") || strings.Contains(file.Name(), ".jpeg") {
				println("OCR---" + file.Name() + "--BASE64编码中···")
				imageBase64 := readImageBase64("./images/" + file.Name())
				imageBase64Size := len(imageBase64)
				fmt.Printf("OCR---" + file.Name() + "--BASE64编码成功---BASE64大小：%d字节",imageBase64Size)
				println()
				//判断base64 长度 不能超过6Mb
				if imageBase64Size < 58720244 {
					println("OCR---正在转换....")
					request := ocr.NewGeneralHandwritingOCRRequest()
					request.ImageBase64 = common.StringPtr(imageBase64)
					response, err := client.GeneralHandwritingOCR(request)
					if _, ok := err.(*errors.TencentCloudSDKError); ok {
						fmt.Println("OCR---" + file.Name() + "--转换失败---%s",err)
					}else {
						fmt.Println("OCR---" + file.Name() + "--转换成功---准备输出结果")
						var resultStr = ""
						for _, detection := range response.Response.TextDetections {
							resultStr+=*detection.DetectedText+"\n"
						}
						var outPutResultPath = "./ocr_out/"+file.Name()+".OCR_RESULT.txt"
						fmt.Printf("OCR---" + file.Name() + "--转换成功---结果写入至 %s 中····\n",outPutResultPath)
						resultFile, err := os.OpenFile(outPutResultPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
						if err!=nil {
							fmt.Printf("OCR---" + file.Name() + "--转换成功---结果写入至%s文件失败，固直接输出结果----------------START",outPutResultPath)
							fmt.Println(resultStr)
							fmt.Printf("OCR---" + file.Name() + "--转换成功---结果写入至%s文件失败，固直接输出结果----------------END",outPutResultPath)
						}else {
							//及时关闭file句柄
							defer resultFile.Close()
							//写入文件时，使用带缓存的 *Writer
							write := bufio.NewWriter(resultFile)
							write.WriteString(resultStr)
							//Flush将缓存的文件真正写入到文件中
							write.Flush()
							fmt.Printf("OCR---" + file.Name() + "--转换成功---结果写入至%s 成功\n",outPutResultPath)
						}
					}
				}else {
					println("OCR---" + file.Name() + "--FAIL---当前BASE64编码过大")
				}

			} else {
				println("OCR---" + file.Name() + "--FAIL---不支持图片格式")
			}
			println("OCR---" + file.Name() + "-----------------------END\n\n")
		}
	}
	println("OCR======================END-==============================================END")
}
/**
读取图片的base64
*/
func readImageBase64(filePath string) string {
	//读原图片
	ff, _ := os.Open(filePath)
	defer ff.Close()
	sourceBuffer := make([]byte, 500000)
	n, _ := ff.Read(sourceBuffer)
	//base64压缩
	sourceString := base64.StdEncoding.EncodeToString(sourceBuffer[:n])
	return sourceString
}
